import _ from 'lodash';

type GlobalStateInstance = Record<string | symbol, any>;

type Listener = (target: GlobalStateInstance, prop: string | symbol, newValue: any) => void;

export interface SubAppMenu {
  id?: string,
  path?: string,
  title?: string,
  children?: Array<SubAppMenu>,
  href?: string,
  isLocked?: boolean,
}

export interface SubAppMenuConfig {
  menu: Array<SubAppMenu>,
  onClickMenuItem: (menu: SubAppMenu) => void,
}

export const StateScopes = {
  EntrustMenus: 'entrustMenus',
};

export default class GlobalState {
  static listeners: Array<Listener> = [];
  static instance = window.globalState;

  static init = () => {
    if (!_.isEmpty(GlobalState.instance)) {
      return;
    }
    const initialState = {
      entrustMenus: {},
    };
    const stateProxy = new Proxy(initialState as GlobalStateInstance, {
      get: (target, prop) => {
        return target[prop];
      },
      set: (target, prop, newValue) => {
        GlobalState.listeners.forEach((listener) => {
          listener(target, prop, newValue);
        });
        return true;
      },
    });
    window.globalState = stateProxy;
    GlobalState.instance = window.globalState;
  };

  static addListener = (listener: Listener) => {
    GlobalState.listeners.push(listener);
  };

  static remoteListener = (listener: Listener) => {
    GlobalState.listeners = _.remove(GlobalState.listeners, (item) => item === listener);
  };
}
